{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import jieba\n",
    "import Spider\n",
    "\n",
    "def highlight(item, query: str, side_len: int = 12) -> str:\n",
    "    positions = list()\n",
    "    query_words = list(jieba.cut(query))  # 把生成器强制转换为列表\n",
    "    i = 0\n",
    "    content_lower = item[2].lower()\n",
    "    word_start_map = list()\n",
    "    word_end_map = list()\n",
    "    last_word_end = -1\n",
    "    len_content_lower = len(content_lower)\n",
    "    segments = list()\n",
    "    for keyword in query_words:\n",
    "        idx = content_lower.find(keyword.lower())\n",
    "        positions.append(idx)\n",
    "    for keyword in jieba.cut(content_lower):\n",
    "        # 用于实现提取摘要时“整词切分”，避免出现截取摘要时首尾的词被截断\n",
    "        current_word_start = last_word_end + 1\n",
    "        current_word_end = current_word_start + len(keyword) - 1\n",
    "        for _ in range(current_word_start, current_word_end+1):\n",
    "            word_start_map.append(current_word_start)\n",
    "            word_end_map.append(current_word_end)\n",
    "        last_word_end = current_word_end\n",
    "    positions.sort()\n",
    "    while i < len(positions):\n",
    "        start_pos = max(positions[i] - side_len, 0)\n",
    "        end_pos = min(positions[i] + side_len, len_content_lower-1)\n",
    "        # 用于实现合并相邻且有部分重合的摘要\n",
    "        while (i < len(positions) - 1) and (positions[i+1] - positions[i] < side_len*2):\n",
    "            end_pos = min(positions[i+1] + side_len, len_content_lower-1)\n",
    "            i += 1\n",
    "        start_ellipsis = '...' if start_pos > 0 else ''\n",
    "        end_ellipsis = '...' if end_pos < len_content_lower else ''\n",
    "        segments.append(start_ellipsis + item[2][word_start_map[start_pos]: word_end_map[end_pos]] + end_ellipsis)\n",
    "        i += 1\n",
    "    result = text = item[1] + '<br/>' + ''.join(segments)\n",
    "    text_lower = text.lower()\n",
    "    for keyword in query_words:\n",
    "        # 高亮部分\n",
    "        idx = text_lower.find(keyword.lower())\n",
    "        if idx >= 0:\n",
    "            ori_word = text[idx:idx+(len(keyword))]\n",
    "            result = result.replace(ori_word, f'<span style=\"color:red\";>{ori_word}</span>')\n",
    "    return result\n",
    "\n",
    "\n",
    "class MySearcherC10V0:\n",
    "    \"\"\"\n",
    "    第九次课升级的搜索类版本：\n",
    "    1、优化对多关键词查询的摘要获取\n",
    "    2、优化对多关键词查询的高亮\n",
    "    \"\"\"\n",
    "    def __init__(self, scale: int=1):\n",
    "        self.docs = list()\n",
    "        self.load_data()\n",
    "        if scale > 1:\n",
    "            self.docs *= scale  # 文档规模倍增，用于测试搜索速度\n",
    "        self.cache = dict()\n",
    "        self.vocab = set()\n",
    "        self.lower_preprocess()\n",
    "        jieba.load_userdict('./dict.txt')\n",
    "        self.build_cache()\n",
    "\n",
    "    def load_data(self, data_file_name='./news_list.pkl'):\n",
    "        if os.path.exists(data_file_name):\n",
    "            self.docs = Spider.pickle_load(data_file_name)\n",
    "        else:\n",
    "            Spider.pickle_save(data_file_name)\n",
    "            self.docs = Spider.pickle_load(data_file_name)\n",
    "\n",
    "    def search(self, query):\n",
    "        result = None\n",
    "        for keyword in jieba.cut(query.lower()):\n",
    "            if keyword in self.cache:\n",
    "                if result is None:\n",
    "                    result = self.cache[keyword]\n",
    "                else:\n",
    "                    result = result & self.cache[keyword]\n",
    "            else:\n",
    "                result = set()\n",
    "                break\n",
    "        if result is None:\n",
    "            result = set()\n",
    "        sorted_result = self.rank(query, result)\n",
    "        return sorted_result\n",
    "\n",
    "    def rank(self, query, result_set):\n",
    "        result = list()\n",
    "        for doc_id in result_set:\n",
    "            result.append([doc_id, self.score(self.docs[doc_id], query)])\n",
    "        result.sort(key=lambda x: x[1], reverse=True)\n",
    "        return result\n",
    "\n",
    "    def render_search_result(self, query):\n",
    "        count = 0\n",
    "        result = ''\n",
    "        for item in self.search(query):\n",
    "            count += 1\n",
    "            result += f'{count}[{item[1]}] {highlight(self.docs[item[0]], query)}\\n'\n",
    "        return result\n",
    "\n",
    "    def score(self, item, query):\n",
    "        score = 0\n",
    "        # TODO 对query查询的分词避免重复\n",
    "        for keyword in jieba.cut(query.lower()):\n",
    "            title_score = item[1].lower().count(keyword.lower())\n",
    "            content_score = item[2].lower().count(keyword.lower())\n",
    "            score += title_score * 5 + content_score * 3\n",
    "        return score\n",
    "\n",
    "    def build_cache(self):\n",
    "        \"\"\"用分词（用文档过滤词库）的方式初始化缓存（构建索引）\"\"\"\n",
    "        doc_id = 0\n",
    "        for doc in self.docs:\n",
    "            doc_word_set = set()\n",
    "            for word in jieba.cut_for_search(doc[3]):\n",
    "                if word not in doc_word_set:\n",
    "                    result_item = doc_id\n",
    "                    if word not in self.cache:\n",
    "                        self.cache[word] = {result_item}\n",
    "                    else:\n",
    "                        self.cache[word].add(result_item)\n",
    "                    self.vocab.add(word)\n",
    "                    doc_word_set.add(word)\n",
    "            doc_id += 1\n",
    "\n",
    "    def lower_preprocess(self):\n",
    "        for doc_id in range(len(self.docs)):\n",
    "            self.docs[doc_id].append(\n",
    "                (self.docs[doc_id][1] + ' ' + self.docs[doc_id][2]).lower())\n",
    "\n",
    "    def simple_test(self):\n",
    "        assert(len(self.search('tiktok')) > 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [],
   "source": [
    "class MySearcherC10V1(MySearcherC10V0):\n",
    "    \"\"\"\n",
    "    在score函数里添加停用词\n",
    "    \"\"\"\n",
    "    def __init__(self, scale: int=1, stopwords_file:str = './stopwords.txt'):\n",
    "        super().__init__(scale)\n",
    "        self.stopwords = set()\n",
    "        self.init_stopwords(stopwords_file)\n",
    "\n",
    "    def init_stopwords(self, stopwords_file):\n",
    "        with open(stopwords_file, 'r',encoding='UTF8') as f:\n",
    "            self.stopwords = set(f.read().split())\n",
    "\n",
    "    def score(self, item, query):\n",
    "        score = 0\n",
    "        for keyword in jieba.cut(query.lower()):\n",
    "            weight = 1\n",
    "            if keyword in self.stopwords:\n",
    "                weight = 0.2\n",
    "            title_score = item[1].lower().count(keyword.lower())\n",
    "            content_score = item[2].lower().count(keyword.lower())\n",
    "            score += (title_score * 5 + content_score * 3) * weight\n",
    "        return score"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 2.45 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "searcher_v1 = MySearcherC10V1()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "outputs": [],
   "source": [
    "class MySearcherC10V2(MySearcherC10V0):\n",
    "    \"\"\"\n",
    "    用文档频率对词进行加权\n",
    "    \"\"\"\n",
    "    def __init__(self, scale: int=1):\n",
    "        self.df = dict()\n",
    "        super().__init__(scale)\n",
    "\n",
    "    def build_cache(self):\n",
    "        \"\"\"\n",
    "        用分词（用文档过滤词库）的方式构建索引\n",
    "        \"\"\"\n",
    "        doc_id = 0\n",
    "        for doc in self.docs:\n",
    "            doc_word_set = set()\n",
    "            for word in jieba.cut_for_search(doc[3]):\n",
    "                if word not in doc_word_set:\n",
    "                    result_item = doc_id\n",
    "                    if word not in self.cache:\n",
    "                        self.cache[word] = {result_item}\n",
    "                    else:\n",
    "                        self.cache[word].add(result_item)\n",
    "                    self.vocab.add(word)\n",
    "                    doc_word_set.add(word)\n",
    "                    if word in self.df:\n",
    "                        self.df[word] += 1\n",
    "                    else:\n",
    "                        self.df[word] = 1\n",
    "            doc_id += 1\n",
    "\n",
    "    def score(self, item, query):\n",
    "        score = 0\n",
    "        for keyword in jieba.cut(query.lower()):\n",
    "            title_score = item[1].lower().count(keyword.lower())\n",
    "            content_score = item[2].lower().count(keyword.lower())\n",
    "            score += (title_score * 5 + content_score * 3) / len(item[2]) / self.df[keyword]\n",
    "        return score"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 1.63 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "searcher_v2 = MySearcherC10V2()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1[0.00514408833827094] <span style=\"color:red\";>华为</span>供应链公司：已向<span style=\"color:red\";>华为</span>P50<span style=\"color:red\";>手机</span>供货，供货时间有延后<br/>据<span style=\"color:red\";>华为</span><span style=\"color:red\";>手机</span>供应链公司，该公司已逐......品牌荣耀出售给了由30多家<span style=\"color:red\";>中国</span>公司组成的财团，以帮...\n",
      "2[0.0027402693446736907] 传<span style=\"color:red\";>华为</span>预计今年智能<span style=\"color:red\";>手机</span>出货量同比减少60%，降至7000万部<br/>...，据供应链消息人士透露，<span style=\"color:red\";>华为</span>已通知其供应商，预计......7000万至8000万部智能<span style=\"color:red\";>手机</span>的零部件。而且<span style=\"color:red\";>华为</span>的零部......品牌荣耀出售给了由30多家<span style=\"color:red\";>中国</span>公司组成的财团，以帮...\n",
      "3[0.0023471858035917902] <span style=\"color:red\";>华为</span>将在英国起诉汇丰，要拿到孟晚舟案关键文件<br/>...》消息，当地时间12日，<span style=\"color:red\";>中国</span><span style=\"color:red\";>华为</span>公司首席财务官孟晚舟......发生了很多事，有关于<span style=\"color:red\";>华为</span><span style=\"color:red\";>手机</span>出货量的报道，也有关...\n",
      "4[0.0020744774812359295] 外媒：夺回<span style=\"color:red\";>华为</span>失去的市场，荣耀仍能重现辉煌<br/>荣耀已与<span style=\"color:red\";>华为</span>分道扬镳，并于上个月发......第一款智能V40。虽然这款<span style=\"color:red\";>手机</span>目前只在<span style=\"color:red\";>中国</span>销售，但荣耀仍有可能...\n",
      "5[0.0018481968685021188] 除了欢迎拜登致电<span style=\"color:red\";>华为</span>，任正非还谈了孟晚舟、退休时间、5G转让等<br/>...任正非接受中外媒体采访，就<span style=\"color:red\";>华为</span>发展、产业、个人生活......发生了很多事，有关于<span style=\"color:red\";>华为</span><span style=\"color:red\";>手机</span>出货量的报道，也有关......一方单方面受益。美国公司向<span style=\"color:red\";>中国</span>供应货物，有利于它改...\n",
      "6[0.001530964219311308] 争国内第一！荣耀想打败<span style=\"color:red\";>华为</span>小米，靠3599的V40行么？<br/>...月前，荣耀正式宣布独立。<span style=\"color:red\";>华为</span>官方称这是“产业链的一......问题。更重要的是，其他国产<span style=\"color:red\";>手机</span>品牌已经虎视眈眈，瞄......以及品牌背书等迅速成为了<span style=\"color:red\";>中国</span>互联网<span style=\"color:red\";>手机</span>品牌第一。然...\n",
      "7[0.0007165927004105008] 小米国内机型不再支持自行安装GMS框架，国际版不受影响<br/>...注意到一些报道中提及小米<span style=\"color:red\";>手机</span>不支持GMS服务，事......年5月16日后，美国制裁<span style=\"color:red\";>华为</span>，谷歌的GMS不再为华......月份，美国政府14日将9家<span style=\"color:red\";>中国</span>企业列入所谓“与<span style=\"color:red\";>中国</span>军...\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(searcher_v2.render_search_result('中国华为手机'))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "outputs": [],
   "source": [],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}